//
//  MarketSearchViewController.m
//  yigou
//
//  Created by wangdianlei on 2017/1/9.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//


#import "SearchResultController.h"
#import "TitleView.h"
#import "CommendTribeCell.h"
#import "TribeDetailViewController.h"
@interface SearchResultController () <UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) TitleView *titleView;
@property (strong, nonatomic) UISearchBar *searchbar;
@property (strong, nonatomic)  UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (strong, nonatomic) UIView *bgView;

@property (strong, nonatomic) NSMutableArray *searchKeyList;
@property (weak, nonatomic) UIButton *clearbtn;
@property (weak, nonatomic) UIImageView *clearimg;

@end

@implementation SearchResultController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    UIView *blankView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
    self.tableView.tableFooterView = blankView;
    self.searchbar.text = self.keywords;
    [self loadNetworkDataWithKeyWords:self.keywords];
    self.searchbar.delegate = self;
    self.tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.tableFooterView = [[UIView alloc]init];

}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(goPop)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    [self.titleView addSubview:self.searchbar];
    
    self.titleView = [[TitleView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
    
    self.titleView.backgroundColor = [UIColor clearColor];
    
    [self.titleView addSubview:self.searchbar];
    
    self.navigationItem.titleView = self.titleView;
}

- (void)clickClearBtn {
    [self clearSearchList];
}

#pragma mark - search
- (void)clearSearchList {
    [self.searchKeyList removeAllObjects];
    [UserData setSearchKeyList:self.searchKeyList];
    [self.tableView reloadData];
}


-(UISearchBar *)searchbar{
    if (!_searchbar) {
        _searchbar=[[UISearchBar alloc]initWithFrame:CGRectMake(10, 7, ScreenWidth-20, 30)];
        _searchbar.placeholder=@"搜索你喜欢的部落";
        _searchbar.delegate=self;
        [_searchbar setBackgroundColor:[UIColor clearColor]];
        [[[_searchbar.subviews objectAtIndex:0].subviews objectAtIndex:0] removeFromSuperview];
        _searchbar.showsCancelButton=YES;
        UIButton *cancelBtn=[_searchbar valueForKey:@"_cancelButton"];
        [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        cancelBtn.titleLabel.font=[UIFont systemFontOfSize:14];
        [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [cancelBtn addTarget:self action:@selector(goPop) forControlEvents:UIControlEventTouchUpInside];
        
        //设置光标的颜色
        _searchbar.tintColor=[UIColor blackColor];
        
        
        UITextField *searchFiled=[_searchbar valueForKey:@"_searchField"];
        //设置处于编辑状态
        //[searchFiled becomeFirstResponder];
        
        //输入文本的颜色
        searchFiled.textColor=[UIColor blackColor];
        
        //输入文本字体的大小
        searchFiled.font=[UIFont systemFontOfSize:14];
        
        //输入框的圆角设置
        //        searchFiled.layer.cornerRadius=10;
        //        searchFiled.layer.masksToBounds=YES;
        
        //输入框里面的背景颜色
        searchFiled.backgroundColor=[UIColor whiteColor];
        
        //提示文本的颜色
        [searchFiled setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
        
        //输入框里的图标
        [_searchbar setImage:[UIImage imageNamed:@"boy.jpg"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
        
    }
    return _searchbar;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //[self.searchbar becomeFirstResponder];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)goPop {
    [self.searchbar resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma - mark UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [self.bgView removeFromSuperview];
    [self.tableView reloadData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {

}


- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    NSLog(@"searchBar:%@",searchBar.text);
    self.keywords = searchBar.text;
    [self loadNetworkDataWithKeyWords:self.keywords];
    [self searchBarResignAndChangeUI];
}

//2、UISearchBar结束编辑

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    
    [self searchBarResignAndChangeUI];
    
}

- (void)searchBarResignAndChangeUI{
    
    [_searchbar resignFirstResponder];//失去第一响应
    
    [self changeSearchBarCancelBtnTitleColor:_searchbar];//改变布局
    
}

#pragma mark - 遍历改变搜索框 取消按钮的文字颜色

- (void)changeSearchBarCancelBtnTitleColor:(UIView *)view{
    
    if (view) {
        
        if ([view isKindOfClass:[UIButton class]]) {
            
            UIButton *getBtn = (UIButton *)view;
            
            [getBtn setEnabled:YES];//设置可用
            [getBtn addTarget:self action:@selector(goPop) forControlEvents:UIControlEventTouchUpInside];
            [getBtn setUserInteractionEnabled:YES];
            
            //设置取消按钮字体的颜色“#0374f2”
            
            [getBtn setTitleColor:[UIColor grayColor] forState:UIControlStateReserved];
            
            [getBtn setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];
            
            return;
            
        }else{
            
            for (UIView *subView in view.subviews) {
                
                [self changeSearchBarCancelBtnTitleColor:subView];
                
            }
            
        }
        
    }else{
        
        return;
        
    }
    
}
#pragma mark TableViewDelegate &  DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 150;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CommendTribeCell *cell = GET_CELL(CommendTribeCell, @"CommendTribeCell");
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    CommendTribeModel *model = [[CommendTribeModel alloc]initWithDictionary:self.dataSource[indexPath.row] error:nil];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CommendTribeModel *model = [[CommendTribeModel alloc]initWithDictionary:self.dataSource[indexPath.row] error:nil];
    NSString *tribeId = model.tribe_id;
    TribeDetailViewController *detail = [[TribeDetailViewController alloc]initWithNibName:@"TribeDetailViewController" bundle:nil];
    [self.navigationController pushViewController:detail animated:YES];
    detail.tribeID = tribeId;
    
}

#pragma -mark 数据请求
- (void)loadNetworkDataWithKeyWords:(NSString *)keyword {
    
    self.dataSource = [NSMutableArray new];
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/hytribe/serarchTribe?keyword=%@", APIYIGOU,keyword];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSDictionary *data = [dict objectForKey:@"data"];
        for (NSArray *tmpArr in data) {
            [self.dataSource addObject:tmpArr];
        }
        
        
        __weak __typeof(self) weakself= self;
        dispatch_async(dispatch_queue_create(0, 0), ^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (weakself.dataSource.count == 0) {
                    self.bgView = [[UIView alloc]initWithFrame:self.tableView.frame];
                    //                    view.backgroundColor = [UIColor yellowColor];
                    weakself.tableView.backgroundView = self.bgView;
                    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, (SCREEN_HEIGHT-64)/2-10, SCREEN_WIDTH, 20)];
                    //                    label.backgroundColor = [UIColor redColor];
                    label.textAlignment = NSTextAlignmentCenter ;
                    label.text = @"没有找到您要搜索的部落~~";
                    [self.bgView addSubview:label];
                }else{
                    self.tableView.backgroundView = [[UIView alloc]initWithFrame:self.tableView.frame];
                }
                
                [weakself.tableView reloadData];
            });
        });
        
        
    } error:^(YTKBaseRequest *request) {
        NSData *JSONData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
        [ViewFactory showErrorStrMsg:[responseJSON objectForKey:@"message"]];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
}
@end
